package com.css.openapi.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import feign.FeignException;
import feign.RequestInterceptor;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;


import java.io.IOException;
import java.lang.reflect.Type;



@Slf4j
public class ZrrdkFeignConfig {


    @Bean
    public RequestInterceptor interceptor() {
        return requestTemplate -> {
            String body = JSONUtil.toJsonStr(StrUtil.str(requestTemplate.body(), CharsetUtil.UTF_8));
            log.info("调用自然人代开系统参数：{},authorization:{}", body);
        };
    }


    @Bean
    public Decoder decoder() {
        return new Decoder() {
            @Override
            public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
                String content = IoUtil.read(response.body().asInputStream(), io.netty.util.CharsetUtil.UTF_8);
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(content);
                log.info("调用自然人代开系统出参：{}",JSON.toJSONString(jsonObject));
                if(jsonObject.get("data") instanceof com.alibaba.fastjson.JSONObject){
                    JSONObject data = jsonObject.getJSONObject("data");
                    jsonObject.remove("data");
                    if(CollectionUtil.isNotEmpty(data)) {
                        jsonObject.putAll(data);
                    }
                }
                return jsonObject.toJavaObject(type);
            }
        };
    }

}
